package lab.relaxng.ws.util;

import java.util.logging.Logger;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;

public class DBUtils {

	public static final Logger logger = Logger.getLogger(DBUtils.class.getName());
	
	private static void newSchema(String input, String output) {
		
		Entity schema = new Entity("SchemaConversion");
		schema.setProperty("input",	input);
		schema.setProperty("output", output);
		
		datastore().put(schema);
		
	}
		
	private static Entity getSchema() {
		Query q = new Query("SchemaConversion");
		
		PreparedQuery pq = datastore().prepare(q);
		
		Entity schema = pq.asSingleEntity();		
		
		return schema;
	}
	
	public static void updateSchema(String input, String output) {
		Entity schema = getSchema();
		if (schema == null) {
			newSchema(input, output);
		} else {
			schema.setProperty("input", input);
			schema.setProperty("output", output);
			datastore().put(schema);
		}
	}
	
	public static void updateSchema(String output) {
		Entity schema = getSchema();
		if (schema == null) {
			newSchema("", output);
		} else {
			schema.setProperty("output", output);
		}
		datastore().put(schema);
	}
	
	private static DatastoreService datastore() {
		return DatastoreServiceFactory.getDatastoreService();
	}
	
	public static String getConversion() {
		return getSchema().getProperty("output").toString();
	}
	
	public static void reset() {
		updateSchema("", "");
	}
}
